package com.villaday.idf.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.AppContext;
import com.villaday.idf.AppManager;
import com.villaday.idf.MainActivity;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.Sms;
import com.villaday.idf.model.SmsEntity;
import com.villaday.idf.model.members;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.PreferencesUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
 * 登录的时候绑定检查
 * */
public class BindPhone_V3Activity extends BaseActivity implements OkHttpUtil.OnDataListener {


    @BindView(R.id.img_close)
    ImageView imgClose;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.tv_bind)
    TextView tvBind;
    private String roleType;

    private Gson gson = new GsonBuilder().create();
    private Handler handler = new Handler();
    private LoadingDialog loadingDialog;

    private int type;//0为绑定1为修改

    private final int retryLimit = 120;//重试秒数上限
    private int timeNum = retryLimit;//获取验证码倒计时
    private long getCodeTime;//获取到验证码的时间
    private boolean isRegister;//是否正在注册
    private String correctCode;//正确的验证码
    private String mobile;//获取验证码的手机号

    @Override
    protected int getViewResId() {
        return R.layout.activity_bind_phone__v3;
    }

    @Override
    protected void init() {
        RefreshtokenEntity.BodyBean roleInfo =
                SharedPreferencesUtil.getRoleInfo(this);
        roleType = roleInfo.getMember().getType();

        if ("0".equals(roleType)) {
            imgClose.setVisibility(View.VISIBLE);
        } else {
            imgClose.setVisibility(View.INVISIBLE);

        }

        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(etPhone.getText().toString()) && !TextUtils.isEmpty(s)) {
                    tvBind.setSelected(true);
                } else {
                    tvBind.setSelected(false);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(etCode.getText().toString()) && !TextUtils.isEmpty(s)) {
                    tvBind.setSelected(true);
                } else {
                    tvBind.setSelected(false);

                }

                PhoneUtil.isEditError2(s.toString(), etPhone);
                if (s.length() == 11 && s.toString().matches(Constant.Strings.RegexMobile)) {
                    tvSend.setSelected(true);
                    tvSend.setClickable(true);
                } else {
                    tvSend.setClickable(false);
                    tvSend.setSelected(false);

                    tvSend.setText("获取验证码");
                    handler.removeCallbacksAndMessages(null);
                    timeNum = retryLimit;
                    isRegister = false;
                    correctCode = "";
                    mobile = "";
                    getCodeTime = 0;

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({R.id.img_close, R.id.tv_send, R.id.tv_bind})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_close:
                onBackPressed();
                break;
            case R.id.tv_send:
                getCode();
                break;
            case R.id.tv_bind: {//绑定
                String phone = etPhone.getText().toString();
                String code = etCode.getText().toString();

                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.initToast(this, "请输入手机号");
                } else if (TextUtils.isEmpty(code)) {
                    ToastUtil.initToast(this, "请输入短信验证码");
                } else {
                    loadingDialog = LoadingDialog.newInstance("绑定中...");
                    loadingDialog.show(getFragmentManager());
                    Map<String, Object> map = new HashMap<>();
                    OkHttpUtil.postJson(this, Constant.URL.members, new members(1, phone, code), map, this);
                }
                break;
            }
        }
    }


    //获取验证码
    private void getCode() {
        if (tvSend.isSelected()) {
            String mobile = etPhone.getText().toString();
            if (mobile.length() == 0) {
                ToastUtil.initToast(this, "手机号码不能为空");
            } else if (!mobile.matches(Constant.Strings.RegexMobile)) {
                ToastUtil.initToast(this, "请输入正确的手机号码");
            } else {
                tvSend.setSelected(false);
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(this, Constant.URL.sms, new Sms(402, mobile), map, this);
                //设置XX秒后重试
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (tvSend != null) {
                            tvSend.setText("点击重新发送 (" + timeNum + ")");
                            if (timeNum > 0) {
                                handler.postDelayed(this, 1000);
                                timeNum--;
                            } else {
                                tvSend.setText("获取验证码");
                                timeNum = retryLimit;
                                if (etPhone.getText().length() == 11) {
                                    etCode.setSelected(true);
                                }
                            }
                        }
                    }
                });

            }
        } else {
            //ToastUtil.initToast(this, "请先输入手机号");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);

        }

    }

    @Override
    public void onBackPressed() {

        if ("0".equals(roleType)) {
            //初始化推送
            AppContext.getInstance().initPush();
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        } else {
            SharedPreferencesUtil.saveToken(this, "");
            AppManager.getAppManager().AppExit(this);

        }

    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.members.equals(url)) { //绑定手机号
                dismissLoading();
                LogeUtil.e("members", json);
                SmsEntity se = gson.fromJson(json, SmsEntity.class);
                if (Constant.Strings.SUC.equals(se.getCode())) {
                    //初始化推送
                    AppContext.getInstance().initPush();

                    ToastUtil.initToast(this, se.getMsg());
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtil.initToast(this, se.getMsg());
                }
            } else if (Constant.URL.sms.equals(url)) {
                LogeUtil.e("sms", json);
                SmsEntity se = gson.fromJson(json, SmsEntity.class);
                if (Constant.Strings.SUC.equals(se.getCode())) {
                    ToastUtil.initToast(this, "发送成功");
                } else {
                    ToastUtil.initToast(this, "发送失败");
                }
            }
        }

    }


    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onFailure(String url, String error) {

    }
}
